import Pinyin from 'js-pinyin'; //将汉字转为拼音
Pinyin.setOptions({ charCase: 1 });
import { requestMagicApi } from '/@/api/magicApi';
import { useUserStore } from '/@/store/modules/user';
import { BasicColumn } from '/@/components/Table';
import { isNil } from 'lodash-es';
import opencc from 'node-opencc';

//setOptions中传入对象，对象可传两个参数
//charCase： 输出拼音的大小写模式，0-首字母大写；1-全小写；2-全大写
//checkPolyphone：是否检查多音字
//方法：1.getCamelChars: 获取拼音首字母  2.getFullChars: 获取拼音

/* 判断字符串是否有中文 有则在前面添加下划线（第一个字符不添加）并转换成小写拼音 */
export function changeToPinyin(label: string, isUpper?: boolean) {
  const labelArr = label.split('');
  let fieldName = '';
  labelArr.map((item: string, index: number) => {
    const reg = /^[\u4e00-\u9fa5]+$/;
    item = opencc.traditionalToSimplified(item);
    fieldName += reg.test(item) && index !== 0 ? '_' + item : item;
  });
  const pinyin = Pinyin.getFullChars(fieldName.replace(/\s+/g, ''));
  return isUpper ? pinyin.toUpperCase() : pinyin;
}

/* 如果没有下划线，不需要处理
如果有下划线，用下划线切割，第一个下划线左边的全部小写，后面的首字母大写，首字母后面的全部小写 */
export function camelCaseString(string: string) {
  if (!string) return;
  const stringLower = string.toLowerCase();
  const len = stringLower.length;
  let str = '';
  for (let i = 0; i < len; i++) {
    const c = stringLower.charAt(i);
    if (c === '_') {
      if (++i < len) {
        str = str.concat(stringLower.charAt(i).toUpperCase());
      }
    } else {
      str = str.concat(c);
    }
  }
  return str;
}

export async function apiConfigFunc(apiConfig, isCustomForm = false, formModel?) {
  if (!apiConfig?.path) return [];
  const queryParam = {};
  const headerParam = {};
  const bodyParam = {};
  for (const param of apiConfig?.apiParams) {
    //queryString
    if (param.key === '1' && param.tableInfo && param.tableInfo.length) {
      for (const query of param.tableInfo) {
        queryParam[query.name] = getParamsValue(query, formModel, isCustomForm);
      }
    }
    //header
    if (param.key === '2' && param.tableInfo && param.tableInfo.length) {
      for (const head of param.tableInfo) {
        headerParam[head.name] = getParamsValue(head, formModel, isCustomForm, true);
      }
    }
    //body
    if (param.key === '3' && param.tableInfo && param.tableInfo.length) {
      for (const body of param.tableInfo) {
        bodyParam[body.name] = getParamsValue(body, formModel, isCustomForm);
      }
    }
  }
  const res = await requestMagicApi({
    method: apiConfig?.method,
    url: apiConfig.path,
    headers: headerParam,
    body: bodyParam,
    query: queryParam,
  });
  if (res && Array.isArray(res)) return res; //不分页接口
  if (res && Array.isArray(res.list)) return res.list; //分页接口
  return res;
}

function getParamsValue(params, formModel, isCustomForm, isHeaders: Boolean = false) {
  const userStore = useUserStore();
  let value;
  if (params.bindType === 'value') {
    value = params.value;
  } else if (params.bindType === 'data') {
    const paramsArr = params.value.split('-');
    if (paramsArr[0] === '3') {
      //当前信息
      value = isHeaders
        ? encodeURIComponent(userStore.getUserInfo[paramsArr[1]])
        : userStore.getUserInfo[paramsArr[1]];
    } else {
      if (!formModel) return;
      const headerValue = isCustomForm
        ? formModel[paramsArr[0]!]
        : formModel[camelCaseString(paramsArr[0])!];
      value = isHeaders ? encodeURIComponent(headerValue) : headerValue;
    }
  }

  return value;
}

/**
 * 根据列表值 生成table html
 */
export function generateTableHtml(columns: BasicColumn[], datas: Recordable[]): string {
  const headArray: {
    key: string;
    name: string;
  }[] = [];
  const bodySortArray: string[][] = [];

  let result = `<table>`;

  result += `<tr>`;
  //遍历所有列配置 设置为表头
  for (const col of columns) {
    if (col.dataIndex) {
      headArray.push({
        key: col.dataIndex as string,
        name: col.title as string,
      });
    }
    result += `<th>${col.title}</th>`;
  }
  result += `</tr>`;
  //遍历所有数据

  for (const item of datas) {
    result += `<tr>`;
    const row: string[] = [];
    for (const head of headArray) {
      const index = Object.keys(item).indexOf(head.key);
      row[index] = item[head.key];
      result += `<td>${item[head.key]}</td>`;
    }
    bodySortArray.push(row);
    result += `</tr>`;
  }

  result += '</table>';
  return result;
}

/**
 * 根据列表值 生成table html
 */
export function generateTableJson(columns: BasicColumn[], datasource: Recordable[]): Recordable[] {
  const result: Recordable[] = [];

  for (const item of datasource) {
    //替换所有key
    const newRow: Recordable = {};
    Object.keys(item).forEach((key) => {
      const col = columns.find((x) => x.dataIndex == key);
      if (col?.title) {
        newRow[col?.title as string] = isNil(item[key]) ? '' : item[key];
      }
    });
    result.push(newRow);
  }

  return result;
}

export function checkTabCanDelete(layout) {
  let count = 0;
  for (let i = 0; i < layout.length; i++) {
    const o = layout[i];
    for (let i = 0; i < o.list.length; i++) {
      const k = o.list[i];
      if (k.type == 'form' || k.type == 'one-for-one') {
        count += 1;
        break;
      } else if (k.type == 'tab' || k.type == 'card' || k.type == 'grid') {
        count = checkTabCanDelete(k.layout);
        if (count > 0) break;
      } else if (k.options?.required) {
        count += 1;
        break;
      }
    }
    if (count > 0) break;
  }
  return count;
}
